package com.ruoyi.web.controller.gym;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.FileTypeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 健身房控制器
 */
@RestController
@RequestMapping("/gym")
public class GymController extends BaseController {
    
    @Value("${ruoyi.profile}")
    private String uploadPath;

    @PostMapping("/uploadImage")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        try {
              System.out.println("当前使用的上传路径: " + uploadPath);
            String originalFilename = file.getOriginalFilename();
            String suffix = FileTypeUtils.getFileType(originalFilename);
            String fileName = UUID.randomUUID().toString() + "." + suffix;
            String datePath = DateUtils.datePath();
            
            // 使用 Paths 类来处理路径拼接
            Path fullPath = Paths.get(uploadPath, "gym", "images", datePath);
            File dir = fullPath.toFile();
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw new IOException("Failed to create directory: " + fullPath);
                }
            }
            
            // 保存文件
            File targetFile = new File(dir, fileName);
            file.transferTo(targetFile);
            
            // 返回访问路径
            String url = "/profile/gym/images/" + datePath + "/" + fileName;
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", datePath + "/" + fileName);
            ajax.put("originalFilename", originalFilename);
            
            return ajax;
            
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}